package com.cycling.app.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.cycling.app.R;
import com.cycling.app.utils.DribblePrefs;
import com.cycling.app.utils.overlayutil.PoiOverlay;
import com.cycling.app.view.SquareImageView;

import java.util.Locale;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, OnGetGeoCoderResultListener, DribblePrefs.DribbleLoginStatusListener {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocClient;
    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    private MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationData myLocData;
    private boolean isFirstLoc = true;
    private BitmapDescriptor mCyclingBmp;
    private NavigationView mNavigationView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mLocClient != null) {
                    isFirstLoc = true;
                    mLocClient.start();
                }
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
        mNavigationView.setNavigationItemSelectedListener(this);

        initNavigationView();

        DribblePrefs.get().addLoginStatusListener(this);

        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        initMapView();
    }

    private void initNavigationView() {
        View headerView = mNavigationView.getHeaderView(0);
        ImageView avatar = (ImageView) headerView.findViewById(R.id.iv_user_avatar);
        TextView username = (TextView) headerView.findViewById(R.id.tv_username);
        TextView money = (TextView) headerView.findViewById(R.id.tv_money);
        if (!DribblePrefs.get().isLoggedIn()) {
            username.setText("点击头像登录");
            money.setText("");
            avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
            });
        } else {
            username.setText(DribblePrefs.get().getUser_name());
            money.setText(String.format(Locale.getDefault(), "余额：￥%s", DribblePrefs.get().getMoney()));
            avatar.setOnClickListener(null);
        }
    }

    private void initMapView() {
        BaiduMapOptions options = new BaiduMapOptions();
        options.scaleControlEnabled(false);
        options.zoomControlsEnabled(false);
        mMapView = new MapView(this, options);
        ViewGroup container = (ViewGroup) findViewById(R.id.map_view_container);
        container.addView(mMapView, new ViewGroup.LayoutParams(-1, -1));

        mBaiduMap = mMapView.getMap();

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);

        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(3000);//设置定位时间间隔（每隔3秒定位一次，成功后可向服务器发送无人车状态）可修改
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    private void checkOrCreateCyclingBmp() {
        if (mCyclingBmp != null) return;

        SquareImageView view = new SquareImageView(MainActivity.this);
        view.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
        view.setBackgroundResource(R.drawable.cycling_circle_blue_button);
        view.setImageResource(R.drawable.ic_action_cycling);
        int padding = dp2px(MainActivity.this, 10);
        view.setPadding(padding, padding, padding, padding);
        mCyclingBmp = BitmapDescriptorFactory.fromView(view);
    }

    /**
     *  附近检索 
     */
    private void nearbySearch(LatLng latitude) {
        mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                .location(latitude));
    }

    public void jumpToUse(View view){
        startActivity(new Intent(MainActivity.this, UseActivity.class));
    }

    @Override
    public void onDribbleLogin() {
        initNavigationView();
    }

    @Override
    public void onDribbleLogout() {
        initNavigationView();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_route) {
            // Handle the camera action
        } else if (id == R.id.nav_wallet) {

        } else if (id == R.id.nav_invite) {

        } else if (id == R.id.nav_use) {

        } else if (id == R.id.nav_settting) {

        } else if (id == R.id.nav_about) {

        } else if (id == R.id.nav_logout) {
            new AlertDialog.Builder(MainActivity.this)
                    .setMessage("是否确认退出登录？")
                    .setNegativeButton("不了", null)
                    .setPositiveButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            DribblePrefs.get().logout();
                        }
                    }).show();
        }

//        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        DribblePrefs.get().removeLoginStatusListener(this);
        super.onDestroy();
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        if (reverseGeoCodeResult == null || reverseGeoCodeResult.error == ReverseGeoCodeResult.ERRORNO.RESULT_NOT_FOUND) {
            Log.e("TAG", "没有找到结果");
            return;
        }
        if (reverseGeoCodeResult.error == ReverseGeoCodeResult.ERRORNO.NO_ERROR) {// 检索结果正常返回 
            mBaiduMap.clear();
            MyPoiOverlay poiOverlay = new MyPoiOverlay(mBaiduMap);
            poiOverlay.setData(reverseGeoCodeResult.getPoiList());// 设置POI数据  
            mBaiduMap.setOnMarkerClickListener(poiOverlay);
            poiOverlay.addToMap();// 将所有的overlay添加到地图上  
        }
    }

    public class MyPoiOverlay extends PoiOverlay {
        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int i) {
            startActivity(new Intent(MainActivity.this, UseActivity.class));
            return true;
        }

        @NonNull
        @Override
        public BitmapDescriptor getPoiMarker() {
            checkOrCreateCyclingBmp();
            return mCyclingBmp;
        }
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            myLocData = new MyLocationData.Builder()
                    .speed(location.getSpeed())
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(myLocData);
            LatLng ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            if (isFirstLoc) {
                isFirstLoc = false;
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                nearbySearch(ll);
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

    }

    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }
}
